package de.hauck.rtmidlet.utils;

import java.util.Vector;

import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import de.hauck.rtmidlet.views.CanvasCharts;

public class ImageManipulatorThread implements Runnable {

	private boolean quit = false;
	private Vector queue = new Vector();
	private Thread thread;
	private int _width,_height;
	private Displayable _dble;
	private int _index;

	public ImageManipulatorThread(Displayable dble) {
		_dble=dble;
		new Thread(this).start();
	}
	
	public ImageManipulatorThread(int width, int height, int index) {
		_width=width;
		_height=height;
		_index=index;
		new Thread(this).start();
		
	}

	public void run() {
		Object o;

		while (!quit) { // busy wait!
			o = null;

			synchronized (queue) {
				if (queue.size() > 0) {
					o = queue.elementAt(0);
					queue.removeElementAt(0);
				}
			}

			if (o != null) {
				//do something		
				Image resizedImage = rescaleImage((Image)o);
				((CanvasCharts)_dble).setOverviewImage(resizedImage,_index);
			}
		}
	}

	public boolean addToQueue(Object o, int index) {
		if (!quit) {
			_index=index;
			queue.addElement(o);
			return true;
		}

		return false;
	}

	public void quit() {
		quit = true;
	}
	
	private Image rescaleImage(Image image) {
		System.out.println("Scaling image in thread");
		int sourceWidth = image.getWidth();
		int sourceHeight = image.getHeight();

		Image newImage = Image.createImage(_width, _height);
		Graphics g = newImage.getGraphics();

		for (int y = 0; y < _height; y++) {
			for (int x = 0; x < _width; x++) {
				g.setClip(x, y, 1, 1);
				int dx = x * sourceWidth / _width;
				int dy = y * sourceHeight / _height;
				g
						.drawImage(image, x - dx, y - dy, Graphics.LEFT
								| Graphics.TOP);
			}
		}

		return Image.createImage(newImage);
	}
	
	public void setSizes(int width, int height) {
		_width=width;
		_height=height;
	}
}
